package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

/**
 * @author 杰哥不要啦~
 * @date 2021/11/3
 */
@DubboService
public class UserLocationApiImpl implements UserLocationApi{

    @Autowired
    private MongoTemplate mongoTemplate;
    //更新地理位置
    @Override
    public Boolean updateLocaton(Long userId, Double longitude, Double latitude, String address) {
        try{
        //1、根据用户id查询位置信息
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
        //2、如果不存在用户位置信息，保存
        if (location == null){
            location = new UserLocation();
            location.setUserId(userId);
            location.setAddress(address);
            location.setCreated(System.currentTimeMillis());
            location.setUpdated(System.currentTimeMillis());
            location.setLastUpdated(System.currentTimeMillis());
            location.setLocation(new GeoJsonPoint(longitude,latitude));
            mongoTemplate.save(location);
        }else {
            //3、如果存在，更新
            Update update = Update.update("location",new GeoJsonPoint(longitude, latitude))
                    .set("updated", System.currentTimeMillis())
                    .set("lastUpdated", location.getUpdated());
            mongoTemplate.updateFirst(query,update,UserLocation.class);
        }
        return true;
    } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
